<?php

namespace app\admin\controller\qingdongwms\weixin;

use app\common\controller\Backend;
use addons\qingdongwms\model\StaffDepartment;
use addons\qingdongwms\model\DingStaff;
use addons\qingdongwms\model\DingCustomer;
use addons\qingdongwms\model\DingContacts;
use addons\qingdongwms\model\AdminConfig;
use addons\qingdongwms\model\Staff;
/**
 * 微信同步
 */
class Weixin extends Backend
{
    public function __construct(){
        $this->corpid =AdminConfig::where(array('field'=>'corpid'))->value('value');
        $corpsecret=AdminConfig::where(array('field'=>'corpsecret'))->value('value');
        $url ='https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid='.$this->corpid.'&corpsecret='.$corpsecret;
        $token = $this->http_get($url);
        $token = json_decode($token,true);
        if($token['errcode'] != 0){
            $this->error($token['errmsg']);
        }
        $this->access_token = $token['access_token'];
    }

    /**
     * 获取部门
     */
    public function index(){
        //获取部门
        $url = 'https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token='.$this->access_token;
        $department = $this->http_get($url);
        $department = json_decode($department,true);
        if($department['errcode'] != 0){
            $this->error($department['errmsg']);
        }
        foreach($department['department'] as $k=>$v){
            $departmentData = StaffDepartment::where(array('number'=>$this->corpid.'_'.$v['id']))->find();
            if($departmentData){
                continue;
            }
            $pid = 0;
            if($v['parentid'] !=0){
                $pid = StaffDepartment::where(array('number'=>$this->corpid.'_'.$v['parentid']))->value('id');
            }
            $deRes = array(
                'type'=>1,
                'name'=>$v['name'],
                'pid'=>$pid,
                'number'=>$this->corpid.'_'.$v['id']
            );
            $departmentInfo = StaffDepartment::create($deRes);
            if(!$departmentInfo){
                $this->error('同步失败');
            }
        }
        $this->success('同步成功');
    }
    /**
     * 获取员工
     */
    public function staffinfo(){

        $department = StaffDepartment::where(array('type'=>1))->select();
        if(!$department){
            $this->error('部门为空,请先同步部门');
        }
        foreach($department as $k=>$v){
            $deptId = explode('_',$v['number']);
            $url ='https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token='.$this->access_token.'&department_id='.$deptId[1];
            $staff =$this->http_get($url);
            $staff = json_decode($staff,true);
            if($staff['errcode'] != 0 || !$staff['userlist']){
                continue;
            }
            foreach($staff['userlist'] as $ks=>$vs){
                //重复员工记录不存储
                $staffFind = DingStaff::where(array('user_id' =>$vs['userid'],'type'=>1))->find();
                if($staffFind){
                    continue;
                }
                $department = StaffDepartment::where(array('number'=>$deptId[0].'_'.$vs['department'][0]))->value('id');
                $staffUser = array(
                    'type' => 1,
                    'dept_id' =>$department,
                    'user_id' =>$vs['userid'],
                    'name' =>filter_Emoji($vs['name']),
                    'mobile' => isset($vs['mobile']) ? $vs['mobile'] : $vs['telephone'],
                    'status' =>0,
                );
                DingStaff::create($staffUser);
            }
        }
        $this->success('同步成功');
    }
    /**
     * 批量获取客户
     */
    public function customer(){

        $DingStaff = DingStaff::where(array('type'=>1))->limit(100)->select();
        if(!$DingStaff){
            $this->error('员工为空,请先同步员工为空');
        }
        $staffUser = array();
        foreach($DingStaff as $k=>$v){
            $staffUser[] = $v['user_id'];
        }
        $user = array(
            'userid_list'=>$staffUser,
            'cursor'=>'',
            'limit'=>100
        );
        $url ='https://qyapi.weixin.qq.com/cgi-bin/externalcontact/batch/get_by_user?access_token='.$this->access_token;
        $customer = $this->http_post($url,json_encode($user));
        $customer = json_decode($customer,true);
        if($customer['errcode'] != 0){
            $this->error($customer['errmsg']);
        }
        foreach($customer['external_contact_list'] as $ks=>$vs){
            $customerFind = DingCustomer::where(array('instance_id'=>$vs['external_contact']['external_userid']))->find();
            if($customerFind){
                continue;
            }
            $data = $vs;
            $instance_id = isset($data['external_contact']['external_userid']) ? $data['external_contact']['external_userid'] : '';
            $customerName = isset($data['external_contact']['name']) ? addslashes(filter_Emoji($data['external_contact']['name'])) : '';
            $owner_staff_id=isset($data['follow_info']['userid']) ? $data['follow_info']['userid'] : '';
            $create_staff_id=isset($data['follow_info']['userid']) ? $data['follow_info']['userid'] : '';
            $createtime = isset($data['follow_info']['createtime']) ? $data['follow_info']['createtime'] : '';
            $updatetime = isset($data['follow_info']['createtime']) ? $data['follow_info']['createtime'] : '';

            $customerData = array(
                'type' => 1,
                'instance_id'=>$instance_id,
                'user_id'=>$create_staff_id,
                'name'=>$customerName,
                'owner_staff_id'=>$owner_staff_id,
                'create_staff_id'=>$create_staff_id,
                'createtime'=>$createtime,
                'updatetime'=>$updatetime,
            );
            $customers = DingCustomer::create($customerData);
            $customerId = DingCustomer::getLastInsID();
            //同步联系人
            $contactFind = DingContacts::where(array('instance_id'=>$instance_id))->find();
            if($contactFind){
                DingContacts::where(array('id'=>$contactFind['id']))->update(array('customer_id' =>$customerId));
                continue;
            }
            $contactData = array(
                'type' =>1,
                'instance_id' =>$instance_id,
                'customer_id' =>$customerId,
                'name' =>$customerName,
                'mobile' =>isset($data['follow_info']['remark_mobiles'][0]) ? $data['follow_info']['remark_mobiles'][0] : '',
                'create_staff_id' =>$owner_staff_id,
                'owner_staff_id' =>$create_staff_id,
            );
            DingContacts::create($contactData);
        }

        $this->success('同步成功');

    }
    /**
     * curl请求
     */
    private function http_get($url){
        $oCurl = curl_init();
        if(stripos($url,"https://")!==FALSE){
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if(intval($aStatus["http_code"])==200){
            return $sContent;
        }else{
            return false;
        }
    }
    /**
     * curl请求
     */
    private function http_post($url,$param,$post_file=false){
        $oCurl = curl_init();
        if(stripos($url,"https://")!==FALSE){
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        if (is_string($param) || $post_file) {
            $strPOST = $param;
        } else {
            $aPOST = array();
            foreach($param as $key=>$val){
                $aPOST[] = $key."=".urlencode($val);
            }
            $strPOST =  join("&", $aPOST);
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($oCurl, CURLOPT_POST,true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if(intval($aStatus["http_code"])==200){
            return $sContent;
        }else{
            return false;
        }
    }
    public function mobile(){
        $mobile = input('mobile');
        if(!$mobile){
            $this->error('请绑定员工手机号');
        }
        $user = array(
            'mobile'=>$mobile,
        );
        $url ='https://qyapi.weixin.qq.com/cgi-bin/user/getuserid?access_token='.$this->access_token;
        $customer = $this->http_post($url,json_encode($user));
        $result = json_decode($customer,true);
        if($result['errcode'] ==0 ){
            Staff::where(['mobile'=>$mobile])->update(['wx_userid'=>$result['userid']]);

        }
        dump($result);exit;
    }

}